import axios from 'axios';
import { Notification } from 'element-ui';
import Storage from './storage';
import VueRouter from 'vue-router';
import { baseUrl } from './config/env';

const router = new VueRouter();
// axios.defaults.baseURL = 'http://sd-wms.martin.net/';



let config = {
	timeout: 8* 1000,
	baseURL: baseUrl + '/api/',
	validateStatus: function (status) {
		return status >= 200 && status < 500; // 默认<300
	},
};



const http = axios.create(config);

http.interceptors.request.use(config => {
	const session = Storage.getSession();
	if (session) {
		// config.headers.Authorization = `Session ${session}`;
		config.url += '?api_token='+session;
	}
	console.log(config.url);
	return config;
}, err => Promise.reject(err));

/**
 * sd-erp api
 */
http.interceptors.response.use(res => {
	console.log(res)
	if (res.status === 401) {
		Notification.error({
			message: 'token过期请重新登入！',
			duration: 3000
		});
		// router.push({path: '/login'});
		// location.reload();
		return Promise.reject(res.data);
	}

	const { data } = res;
	switch(data.status) {
		case 'success':
			return Promise.resolve(data);
		case 'error':
			Notification.error({
				message: data.message,
				duration: 3000
			});
			return Promise.reject(data);
		default:
			Notification.error({
				message: '其他异常！',
				duration: 3000
			});
			return Promise.reject(data);  
    }
}, err => {
	Notification.error({
		message: '服务器异常！',
		duration: 3000
	});
	return Promise.reject(err);  
	
});


export default http;